package lion.framework.core.db.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import javax.sql.DataSource;

import lion.dev.lang.MapJ;
import lion.framework.core.db.DataSourceManager;

public class JDBCDataSource implements DataSource {

	private MapJ config;

	public JDBCDataSource(MapJ config) {

		this.config = config;
	}

	@Override
	public Connection getConnection() throws SQLException {

		return this.getConnection(config.getString("user"), config.getString("password"));
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {

		try {
			Class.forName(DataSourceManager.getJDBCDriver(config.getString("type")));
		} catch (ClassNotFoundException e) {
			throw new SQLException("driver class not found", e);
		}

		return DriverManager.getConnection(String.format(DataSourceManager.getDriverURLTemplate(config.getString("type", "mysql")), config.getString("server", "localhost"),
				config.getInt("port", 3306), config.getString("db")), username, password);
	}

	@Override
	public int getLoginTimeout() throws SQLException {

		// do nothing
		return 0;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {

		// do nothing
		return null;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {

		// do nothing
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {

		return false;
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {

		// do nothing
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {

		// do nothing
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {

		return null;
	}
}
